package com.vainycos.lotterysearch.exception;

import com.vainycos.lotterysearch.enums.ExceptionEnum;
import com.vainycos.lotterysearch.model.base.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("ladder[]GlobalExceptionHandle[]methodArgumentNotValidException[]"
                        + " validate of data exception: message:{},type of exception:{}, stack of exception:{}",
                e.getMessage(), e.getClass(), e);
        log.error("Exception->{}", e);
        return Result.buildFailure(ExceptionEnum.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("ladder[]GlobalExceptionHandle[]methodArgumentNotValidException[]"
                        + " validate of data exception: message:{},type of exception:{}, stack of exception:{}",
                e.getMessage(), e.getClass(), e);
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        return Result.buildFailure("5001", fieldErrors.get(fieldErrors.size() - 1).getDefaultMessage());
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(BusinessException.class)
    public Result businessException(BusinessException e) {
        log.error("businessException:{}", e.getMessage());
        return Result.buildFailure(e.getCode(), e.getMessage());
    }

}
